package com.enjoy.book.action;

import javax.imageio.ImageIO;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
/**
 * 验证码;
 * @author 徐佳澎
 */

@WebServlet(urlPatterns = "/code.let",loadOnStartup = 1)
public class ValCodeServlet  extends HttpServlet {
    Random random =new Random();
    private  String getRandomStr(){
        String str ="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        StringBuilder num =new StringBuilder();
        int times=4;
       for(int i=0;i<times;i++){
           int index =random.nextInt(str.length());
           num.append(str.charAt(index));
       }
        return num.toString();
    }
    private Color getBackColor(){
        int red = random.nextInt(255);
        int green = random.nextInt(255);
        int blue = random.nextInt(255);
        return  new Color(red,green,blue);
    }
    private Color getForeColor(Color backColor){
        int red = 255-backColor.getRed();
        int green = 255-backColor.getGreen();
        int blue = 255-backColor.getBlue();
        return  new Color(red,green,blue);
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /**1.输出图片的类型
         *
         */
        resp.setContentType("image/jpeg");

        BufferedImage bufferedImage =new BufferedImage(80,30, BufferedImage.TYPE_INT_RGB);
        /**3.获取画布
         *
         */
        Graphics g= bufferedImage.getGraphics();
        /**4.获取颜色
         *
         */
        Color bgColor = getBackColor();
        g.setColor(bgColor);
        /**5.画背景
         *
         */
        g.fillRect(0,0,100,50);
        Color foreColor =getForeColor(bgColor);
        g.setColor(foreColor);
        g.setFont(new Font("黑体",Font.BOLD,24));
        String randomStr =getRandomStr();
        /**httpSession 用于验证码验证;
         *
         */
        HttpSession session =req.getSession();
        session.setAttribute("code",randomStr);
        /**画图,将随机字符串写进画布,设置位置
         *
         */
        g.drawString(randomStr,10,20);
        ServletOutputStream print =resp.getOutputStream();
        ImageIO.write(bufferedImage,"jpeg",print);
        /**g.fillRect(0,0,80,30)
         *
         */
    }
}
